# -*- coding: UTF-8 -*-
"""
@Project :xlx-fastapi
@File    :config_dao.py
@Author  :xlx-ali
@Date    :2024/06/24 14:00 星期一
"""
from sqlalchemy import desc

from app.dao.models import XlxConfig
from .base_dao import getDatabaseSession


class ConfigQueryDao(object):
    """网站配置查询类dao"""

    @classmethod
    def findList(cls, field_names: list, **kwargs) -> list[XlxConfig]:
        with getDatabaseSession() as session:
            valid_fields = [getattr(XlxConfig, field_name, None) for field_name in field_names if
                            hasattr(XlxConfig, field_name)]
            if not valid_fields:
                raise ValueError("No valid fields to select.")

            query = session.query(*valid_fields)
            for column, value in kwargs.items():
                if not hasattr(XlxConfig, column):
                    continue

                # 根据值类型，来组装查询条件
                if isinstance(value, tuple):
                    # 范围查询
                    query = query.filter(getattr(XlxConfig, column).between(*value))
                elif isinstance(value, list):
                    # in查询
                    query = query.filter(getattr(XlxConfig, column).in_(value))
                elif isinstance(value, str) and value.find("%") != -1:
                    # 模糊查询
                    query = query.filter(getattr(XlxConfig, column).like(value))
                else:
                    # 等值查询
                    query = query.filter(getattr(XlxConfig, column) == value)
            query = query.order_by(desc(XlxConfig.name))
            result = query.all()
            # data = {}
            # for val in result:
            #     item_data = {}
            #     for field_name in field_names:
            #         item_data[field_name] = getattr(val, field_name, None)
            #     data[item_data['name']] = item_data
        return result

    @classmethod
    def findByName(cls, name: str) -> XlxConfig:
        """单条查询示例"""
        with getDatabaseSession() as session:
            query = session.query(XlxConfig).filter(XlxConfig.name == name)
            result = query.first()
        return result


class ConfigOperateDao(object):
    """操作网站配置相关dao"""

    @classmethod
    def updateAll(cls, data: list[dict]):
        with getDatabaseSession() as session:
            session.bulk_update_mappings(XlxConfig, data)
